package com.sec.android.app.myfiles.receiver;

import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.sec.android.app.myfiles.feature.NotificationMgr;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.util.NotificationUtils;
import com.sec.android.app.myfiles.util.PreferenceUtils;

/**
 * Created by eungho78.lee on 2017-06-26.
 */

public class StorageMonitorReceiver extends BroadcastReceiver {
    private static final String TAG = "StorageMonitorReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            Log.d(TAG, "action : " + action);

            if (!NotificationUtils.canShowGlobalNotification(context)) {
                Log.d(TAG, "This device doesn't support Optimize Storage.");
                return;
            }
            NotificationMgr nm = NotificationMgr.getInstance(context);

            switch (action) {
                case Intent.ACTION_DEVICE_STORAGE_LOW:
                    Log.d(TAG, "Free Space is less than 500 MB.");
                    PreferenceUtils.setExtremelyFullCondition(context, true);
                    NotificationUtils.releaseAlarmWithoutIntervalInitialization(context, AppConstants.ACTION_CHECK_FREE_SPACE);
                    nm.cancelNotification();
                    nm.createNotification(context, AppConstants.NotificationActionType.NONE);
                    break;
                case Intent.ACTION_DEVICE_STORAGE_OK:
                    Log.d(TAG, "Free Space is more than 500 MB.");
                    PreferenceUtils.setExtremelyFullCondition(context, false);
                    nm.cancelNotification();
                    if (NotificationUtils.isPreviousAlarmExist(context)) {
                        NotificationUtils.delayCurrentAlarm(context, AppConstants.ACTION_CHECK_FREE_SPACE);
                    } else {
                        NotificationUtils.registerNewAlarm(context, AppConstants.ACTION_CHECK_FREE_SPACE,
                                AlarmManager.INTERVAL_HOUR, AlarmManager.INTERVAL_HOUR);
                    }
                    break;
            }
        }
    }
}
